package com.elvin.platform.schedule;

import com.alibaba.fastjson.JSONObject;
import com.elvin.platform.beans.ConstantsPath;
import com.elvin.platform.beans.Device;
import com.elvin.platform.service.DeviceService;
import com.elvin.platform.util.HttpUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Component
@Log4j2
public class DeviceTokenScheduledJob {

@Resource
private DeviceService service;
  @Async
  @Scheduled(cron = "0 0 0 1/6 * ?")
  public void scheduledMethod2() {
    log.info("定时器开始DeviceTokenScheduledJob");
    Device entity = new Device();
      entity.setDevType("摄像机");
      List<Device> deviceList = service.selectByDevType(entity);
      for (Device device : deviceList) {
        if(!device.getMasterApikey().isEmpty() && !device.getAccessKey().isEmpty()){
          String accessToken = getAccessToken(device.getMasterApikey(), device.getAccessKey());
          device.setStream(accessToken);
          device.setId(device.getId());
          if(device.getId()!=null){
            service.updateToken(device);
          }
        }
      }
  }

  /**
   * 获取全局token
   */
  public String getAccessToken(String appKey,String appSecret) {
    Map<String, String> requestUrlParam = new HashMap<>();
    requestUrlParam.put("appKey", appKey);
    requestUrlParam.put("appSecret",appSecret);
    JSONObject json = JSONObject.parseObject(HttpUtil.sendPost(ConstantsPath.DEVICE_TOKEN_URL, requestUrlParam));
    String access_token = (String)json.getJSONObject("data").get("accessToken");
    return  access_token;
  }
}
